package com.ocn.li.scmdy.modules.app.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelWriter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.ocn.li.scmdy.common.exception.MyException;

/**
 * 导出Excel工具类
 *
 * @author wanglei
 * @date 2019-04-24 13:21:41
 */
public class ExcelUtils {

	public static void write(ExcelWriter writer, HttpServletResponse response, String fileName) {
		try {
			//response为HttpServletResponse对象
			if (ObjectUtil.isNotNull(response)) {
				ServletUtil.setHeader(response, "Content-Type", "application/octet-stream;charset=utf-8");
				ServletUtil.setHeader(response, "Access-Control-Expose-Headers", "Content-Disposition");
				ServletUtil.setHeader(response, "Content-Disposition", "attachment;filename=" + fileName);
				if (ObjectUtil.isNotNull(writer)) {
					writer.flush(response.getOutputStream());
				}
			}
		} catch (IOException e) {
			throw new MyException("导出EXCEL异常", e);
		} finally {
			if (ObjectUtil.isNotNull(writer)) {
				writer.close();
			}
		}
	}
}
